#include "mainwindow.h"
// #include "ui_mainwindow.h"
#include "libio.h"
#include "libalgorithm.h"
#include <QApplication>
#include <QWidget>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QString>
#include <QMap>
#include <QPixmap>
#include <QRadioButton>
#include <QButtonGroup>
#include <string>
#include <utility>
#include <iostream>
#include <sstream>
#include <vector>
#include <QComboBox>


std::string startstationname;  
std::string endstationname;

RouteInfoWindow::RouteInfoWindow(QString routeInfo, QWidget *parent) 
{
    QLabel *backgroundLabel = new QLabel(this);
    backgroundLabel->setPixmap(QPixmap("./pics/Bus_free.jpg"));
    backgroundLabel->setScaledContents(true); // 自动调整图片大小以适应窗口
    backgroundLabel->setGeometry(0, 0, 400, 400); // 设置背景图片标签的大小为窗口大小

    // 设置标题
    QLabel *titleLabel = new QLabel("路线详细信息", this);
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setStyleSheet("font-size: 24px; font-weight: bold; color :  #ffffff; background-color: rgba(50, 50, 50, 140);");

    // 显示路线信息的标签
    QLabel *infoLabel = new QLabel(routeInfo, this);
    infoLabel->setAlignment(Qt::AlignCenter);
    infoLabel->setStyleSheet("font-size: 18px;");

    // 添加按钮 "所有线路" 和 "最优线路"
    QPushButton *allRoutesButton = new QPushButton("所有线路", this);
    allRoutesButton->setStyleSheet("font-size: 18px;");
    QPushButton *optimalRouteButton = new QPushButton("最优线路", this);
    optimalRouteButton->setStyleSheet("font-size: 18px;");

    // 布局管理
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(titleLabel);
    layout->addWidget(infoLabel);
    layout->addWidget(allRoutesButton);
    layout->addWidget(optimalRouteButton);

    // 连接 "所有线路" 按钮的功能
    connect(allRoutesButton, &QPushButton::clicked, this, [=]() {
        QString allRoutesInfo; 
        std::string info = BusSystem::algorithm::findAllPossibleRoutes(startstationname, endstationname);
        allRoutesInfo = QString::fromStdString(info);
        showNewWindow(allRoutesInfo, "所有线路信息");
    });

    // 连接 "最优线路" 按钮的功能
    connect(optimalRouteButton, &QPushButton::clicked, this, [=]() {
        QString optimalRouteInfo; 
        std::string info;
        std::stringstream ss; 
        ss << BusSystem::algorithm::findDirectRoutes(startstationname, endstationname);
        ss << BusSystem::algorithm::findOptimalRoute(startstationname, endstationname);
        ss << BusSystem::algorithm::findShortestTimeRoute(startstationname, endstationname);
        info = ss.str();
        optimalRouteInfo = QString::fromStdString(info);
        showNewWindow(optimalRouteInfo, "最优线路信息");
    });

    setWindowTitle("路线信息");
    resize(400, 400);
}

// 显示新窗口的方法
void RouteInfoWindow::showNewWindow(const QString &info, const QString &title) 
{
    QWidget *newWindow = new QWidget();
    QLabel *infoLabel = new QLabel(info, newWindow);
    infoLabel->setAlignment(Qt::AlignCenter);
    infoLabel->setStyleSheet("font-size: 18px;");

    QVBoxLayout *layout = new QVBoxLayout(newWindow);
    layout->addWidget(infoLabel);

    newWindow->setWindowTitle(title);
    newWindow->resize(400, 300);
    newWindow->show();
}


// 车次信息窗口类，显示车次的详细信息
TrainInfoWindow::TrainInfoWindow(QString trainInfo, QWidget *parent) 
{
    QLabel *titleLabel = new QLabel("车次详细信息", this);
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setStyleSheet("font-size: 24px; font-weight: bold; color :  #ffffff; background-color: rgba(50, 50, 50, 140);");

    QLabel *infoLabel = new QLabel(trainInfo, this);
    infoLabel->setAlignment(Qt::AlignCenter);
    infoLabel->setStyleSheet("font-size: 18px;");

    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(titleLabel);
    layout->addWidget(infoLabel);

    setWindowTitle("车次信息");
    resize(400, 300);
}

// 修改后的构造函数，接受 NewLine* 参数
AddStationWindow::AddStationWindow(NewLine *line, QWidget *parent):QWidget(parent), newLine(line) 
{
    // 设置标题
    QLabel *titleLabel = new QLabel("添加新站点", this);
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setStyleSheet("font-size: 24px; font-weight: bold; color :  #ffffff; background-color: rgba(50, 50, 50, 140);");

    // 站点名输入框
    QLabel *stationNameLabel = new QLabel("站点名:", this);
    stationNameEdit = new QLineEdit(this);
    stationNameEdit->setPlaceholderText("请输入站点名");

    // 间隔时间输入框
    QLabel *intervalLabel = new QLabel("与下一站的间隔时间（分钟）(输入-1时表示终点):", this);
    intervalEdit = new QLineEdit(this);
    intervalEdit->setPlaceholderText("请输入间隔时间");

    // 添加按钮
    QPushButton *addButton = new QPushButton("添加站点", this);
    addButton->setStyleSheet("font-size: 18px;");

    // "完成"按钮
    QPushButton *finishButton = new QPushButton("完成", this);
    finishButton->setStyleSheet("font-size: 18px;");

    // 布局管理
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(titleLabel);
    layout->addWidget(stationNameLabel);
    layout->addWidget(stationNameEdit);
    layout->addWidget(intervalLabel);
    layout->addWidget(intervalEdit);
    layout->addWidget(addButton);
    layout->addWidget(finishButton);  // 添加 "完成" 按钮到布局中

    // 连接“添加站点”按钮的功能
    connect(addButton, &QPushButton::clicked, this, [=]() {
        QString stationName = stationNameEdit->text().trimmed();
        std::string stationNameStdString = stationName.toStdString();
        QString intervalStr = intervalEdit->text().trimmed();
        std::string intervalStrStdString = intervalStr.toStdString();

        bool isIntervalValid = false;
        int interval = intervalStr.toInt(&isIntervalValid);  // 转换为整数

        if (stationName.isEmpty() || !isIntervalValid) {
            QMessageBox::warning(this, "输入错误", "请输入有效的站点名称和间隔时间！");
        } else {
            // 将站点添加到线路的 stations 向量中
            newLine->stations.push_back({stationName.toStdString(), interval});
            QMessageBox::information(this, "成功", "站点 " + stationName + " 已添加，间隔时间: " + QString::number(interval) + " 分钟");

            // 清空输入框，继续添加站点
            stationNameEdit->clear();
            intervalEdit->clear();
        }
    });

    // 连接“完成”按钮的功能，点击时关闭窗口
    connect(finishButton, &QPushButton::clicked, this, [=]() {
        this->close();  // 关闭当前窗口
    });

    setWindowTitle("添加站点");
    resize(400, 300);
}


QLineEdit *AddStationWindow::stationNameEdit;  // 站点名输入框
QLineEdit *AddStationWindow::intervalEdit;     // 间隔时间输入框


// 删除线路窗口类
DeleteLineWindow::DeleteLineWindow(QWidget *parent) 
{
    QLabel *backgroundLabel = new QLabel(this);
    backgroundLabel->setPixmap(QPixmap("./pics/Bus_snow.jpg"));
    backgroundLabel->setScaledContents(true); // 自动调整图片大小以适应窗口
    backgroundLabel->setGeometry(0, 0, 400, 400); // 设置背景图片标签的大小为窗口大小

    // 设置标题
    QLabel *titleLabel = new QLabel("删除线路", this);
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setStyleSheet("font-size: 24px; font-weight: bold; color :  #ffffff; background-color: rgba(50, 50, 50, 140);");

    // 线路名输入框
    QLabel *lineNameLabel = new QLabel("线路名:", this);
    QLineEdit *lineNameEdit = new QLineEdit(this);
    lineNameEdit->setPlaceholderText("请输入要删除的线路名称");

    // 删除按钮
    QPushButton *deleteButton = new QPushButton("确认删除", this);
    deleteButton->setStyleSheet("font-size: 18px;");

    // 布局管理
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(titleLabel);
    layout->addWidget(lineNameLabel);
    layout->addWidget(lineNameEdit);
    layout->addWidget(deleteButton);

    // 连接“确认删除”按钮的功能
    connect(deleteButton, &QPushButton::clicked, this, [=]() {
        QString lineName = lineNameEdit->text().trimmed();
        std::string lineNameStdString = lineName.toStdString();

        if (lineName.isEmpty()) {
            QMessageBox::warning(this, "输入错误", "请输入线路名称！");
        } else {
            std::cout << "line Info Before" << std::endl;
            echoLineInfo(lineName.toStdString());
            IO::admin::deleteFromJsonbyLine(lineNameStdString);
            std::cout << "line Info After" << std::endl;
            echoLineInfo(lineName.toStdString());
            this->close(); 
        }
    });

    setWindowTitle("删除线路");
    resize(400, 400);
}


// 删除站点窗口类
DeleteStopWindow::DeleteStopWindow(QWidget *parent)
{
    QLabel *backgroundLabel = new QLabel(this);
    backgroundLabel->setPixmap(QPixmap("./pics/Bus_snow.jpg"));
    backgroundLabel->setScaledContents(true); // 自动调整图片大小以适应窗口
    backgroundLabel->setGeometry(0, 0, 400, 400); // 设置背景图片标签的大小为窗口大小

    // 设置标题
    QLabel *titleLabel = new QLabel("删除站点", this);
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setStyleSheet("font-size: 24px; font-weight: bold; color :  #ffffff; background-color: rgba(50, 50, 50, 140);");

    // 线路名输入框
    QLabel *lineNameLabel = new QLabel("线路名:", this);
    QLineEdit *lineNameEdit = new QLineEdit(this);
    lineNameEdit->setPlaceholderText("请输入线路名称");

    // 站点名输入框
    QLabel *stopNameLabel = new QLabel("站点名:", this);
    QLineEdit *stopNameEdit = new QLineEdit(this);
    stopNameEdit->setPlaceholderText("请输入要删除的站点名称");

    // 删除按钮
    QPushButton *deleteButton = new QPushButton("确认删除", this);
    deleteButton->setStyleSheet("font-size: 18px;");

    // 布局管理
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(titleLabel);
    layout->addWidget(lineNameLabel);
    layout->addWidget(lineNameEdit);
    layout->addWidget(stopNameLabel);
    layout->addWidget(stopNameEdit);
    layout->addWidget(deleteButton);

    // 连接“确认删除”按钮的功能
    connect(deleteButton, &QPushButton::clicked, this, [=]() {
        QString lineName = lineNameEdit->text().trimmed();
        std::string lineNameStdString = lineName.toStdString();
        QString stopName = stopNameEdit->text().trimmed();
        std::string stopNameStdString = stopName.toStdString();

        if (lineName.isEmpty() || stopName.isEmpty()) {
            QMessageBox::warning(this, "输入错误", "请完整填写线路名称和站点名称！");
        } else {
            std::cout << "line Info Before" << std::endl;
            echoLineInfo(lineName.toStdString());
            std::cout << "delete stop: " << lineNameStdString << " " << stopNameStdString << std::endl;
            IO::admin::deleteFromJsonbyStation(lineNameStdString, stopNameStdString);
            std::cout << "line Info After" << std::endl;
            echoLineInfo(lineName.toStdString());
            this->close(); 
        }
    });

    setWindowTitle("删除站点");
    resize(400, 400);
}

AddLineWindow::AddLineWindow(QWidget *parent) 
{
    QLabel *backgroundLabel = new QLabel(this);
    backgroundLabel->setPixmap(QPixmap("./pics/Bus_snow.jpg"));
    backgroundLabel->setScaledContents(true); // 自动调整图片大小以适应窗口
    backgroundLabel->setGeometry(0, 0, 400, 400); // 设置背景图片标签的大小为窗口大小

    // 设置标题
    QLabel *titleLabel = new QLabel("添加新线路", this);
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setStyleSheet("font-size: 24px; font-weight: bold; color :  #ffffff; background-color: rgba(50, 50, 50, 140);");

    // 线路名输入框
    QLabel *lineNameLabel = new QLabel("线路名:", this);
    lineNameEdit = new QLineEdit(this);
    lineNameEdit->setPlaceholderText("请输入线路名");

    // 始发时间输入框
    QLabel *startTimeLabel = new QLabel("始发时间:", this);
    startTimeEdit = new QLineEdit(this);
    startTimeEdit->setPlaceholderText("请输入始发时间 (如 06:00)");

    // 末班时间输入框
    QLabel *endTimeLabel = new QLabel("末班时间:", this);
    endTimeEdit = new QLineEdit(this);
    endTimeEdit->setPlaceholderText("请输入末班时间 (如 23:00)");

    // 站点表输入框
    QLabel *stationNumLabel = new QLabel("站点表:", this);
    stationNumEdit = new QLineEdit(this);
    stationNumEdit->setPlaceholderText("以\"站点名,间隔时间;\"形式填写");

    // 下一项按钮
    QPushButton *nextButton = new QPushButton("完成", this);
    nextButton->setStyleSheet("font-size: 18px;");

    // 布局管理
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(titleLabel);
    layout->addWidget(lineNameLabel);
    layout->addWidget(lineNameEdit);
    layout->addWidget(startTimeLabel);
    layout->addWidget(startTimeEdit);
    layout->addWidget(endTimeLabel);
    layout->addWidget(endTimeEdit);
    layout->addWidget(stationNumLabel);
    layout->addWidget(stationNumEdit);
    layout->addWidget(nextButton);
    
    // 连接“下一项”按钮的功能
    connect(nextButton, &QPushButton::clicked, this, [=]() {
        QString lineName = lineNameEdit->text().trimmed();
        std::string lineNameStdString = lineName.toStdString();
        QString startTime = startTimeEdit->text().trimmed();
        std::string startTimeStdString = startTime.toStdString();
        QString endTime = endTimeEdit->text().trimmed();
        std::string endTimeStdString = endTime.toStdString();
        QString stationInfo = stationNumEdit->text().trimmed();
        std::string stationInfoStdString = stationInfo.toStdString();

        std::stringstream ss(stationInfoStdString);
        std::vector<std::string> result;
        std::string token;
        vector<pair<string, int>> stations;
    
        while (std::getline(ss, token, ';')) {
            result.push_back(token);
        }
        for (const auto& str : result) {
            try {
                stations.push_back(parseString(str));
            } catch (const std::exception& e) {
                std::cerr << "Error parsing string: " << str << " - " << e.what() << std::endl;
            }
        }

        if (lineName.isEmpty() || startTime.isEmpty() || endTime.isEmpty()) {
            QMessageBox::warning(this, "输入错误", "请完整填写所有信息！");
        } else {
            // 创建线路信息并将 QString 转换为 std::string
            NewLine *newLine = new NewLine{
                lineName.toStdString(),
                startTime.toStdString(),
                endTime.toStdString(),
                stations
            };
            std::cout << "line Info Before" << std::endl;
            echoLineInfo(lineName.toStdString());
            IO::admin::write2JsonbyLine(*newLine);
            std::cout << "line Info After" << std::endl;
            echoLineInfo(lineName.toStdString());
            
            // // 打开添加站点的窗口并传递新线路信息
            // AddStationWindow *stationWindow = new AddStationWindow(newLine);
            // stationWindow->show();
            this->hide();  // 隐藏当前窗口
        }
    });

    setWindowTitle("添加线路");
    resize(400, 400);
}

// 将字符串解析为 pair<string, int>
std::pair<std::string, int> parseString(const std::string& str) {
    std::istringstream iss(str);
    std::string name;
    int value;
    if (std::getline(iss, name, ',') && (iss >> value)) {
        return {name, value};
    }
    throw std::runtime_error("Invalid format");
}

QLineEdit *AddLineWindow::lineNameEdit;  // 线路名输入框
QLineEdit *AddLineWindow::startTimeEdit;  // 始发时间输入框
QLineEdit *AddLineWindow::endTimeEdit;  // 末班时间输入框
QLineEdit *AddLineWindow::stationNumEdit;

// 更新公交车时间窗口类

ModifyBusTimeWindow::ModifyBusTimeWindow(QWidget *parent)
{
    QLabel *backgroundLabel = new QLabel(this);
    backgroundLabel->setPixmap(QPixmap("./pics/Bus_snow.jpg"));
    backgroundLabel->setScaledContents(true); // 自动调整图片大小以适应窗口
    backgroundLabel->setGeometry(0, 0, 400, 400); // 设置背景图片标签的大小为窗口大小
    // 设置标题
    QLabel *titleLabel = new QLabel("修改发车时间", this);
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setStyleSheet("font-size: 24px; font-weight: bold; color :  #ffffff; background-color: rgba(50, 50, 50, 140);");

    // 线路名输入框
    QLabel *lineNameLabel = new QLabel("线路名:", this);
    QLineEdit *lineNameEdit = new QLineEdit(this);
    lineNameEdit->setPlaceholderText("请输入线路名称");

    // 新的发车时间输入框
    QLabel *newStartTimeLabel = new QLabel("新的发车时间:", this);
    QLineEdit *newStartTimeEdit = new QLineEdit(this);
    newStartTimeEdit->setPlaceholderText("请输入新的发车时间 (如 06:00)");

    // 新的末班时间输入框
    QLabel *newEndTimeLabel = new QLabel("新的末班时间:", this);
    QLineEdit *newEndTimeEdit = new QLineEdit(this);
    newEndTimeEdit->setPlaceholderText("请输入新的末班时间 (如 23:00)");

    // 确认按钮
    QPushButton *confirmButton = new QPushButton("确认修改", this);
    confirmButton->setStyleSheet("font-size: 18px;");

    // 布局管理
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(titleLabel);
    layout->addWidget(lineNameLabel);
    layout->addWidget(lineNameEdit);
    layout->addWidget(newStartTimeLabel);
    layout->addWidget(newStartTimeEdit);
    layout->addWidget(newEndTimeLabel);
    layout->addWidget(newEndTimeEdit);
    layout->addWidget(confirmButton);

    // 连接“确认修改”按钮的功能
    connect(confirmButton, &QPushButton::clicked, this, [=]() 
    {
        QString lineName = lineNameEdit->text().trimmed();
        std::string lineNameStdString = lineName.toStdString();
        QString newStartTime = newStartTimeEdit->text().trimmed();
        std::string newStartTimeStdString = newStartTime.toStdString();
        QString newEndTime = newEndTimeEdit->text().trimmed();
        std::string newEndTimeStdString = newEndTime.toStdString();

        if (lineName.isEmpty() || newStartTime.isEmpty() || newEndTime.isEmpty()) {
            QMessageBox::warning(this, "输入错误", "请完整填写所有信息！");
        } else {
            std::cout << "line Info Before" << std::endl;
            echoLineInfo(lineName.toStdString());
            IO::admin::write2JsonbyLineTime(lineNameStdString, newStartTimeStdString, newEndTimeStdString);
            std::cout << "line Info After" << std::endl;
            echoLineInfo(lineName.toStdString());
        }
    });

    setWindowTitle("修改发车时间");
    resize(400, 400);
}


AddStopWindow::AddStopWindow(NewLine *line, QWidget *parent) : QWidget(parent), newLine(line) {
    QLabel *backgroundLabel = new QLabel(this);
    backgroundLabel->setPixmap(QPixmap("./pics/Bus_snow.jpg"));
    backgroundLabel->setScaledContents(true); // 自动调整图片大小以适应窗口
    backgroundLabel->setGeometry(0, 0, 400, 400); // 设置背景图片标签的大小为窗口大小
    // 设置标题
    QLabel *titleLabel = new QLabel("添加新站点", this);
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setStyleSheet("font-size: 24px; font-weight: bold; color :  #ffffff; background-color: rgba(50, 50, 50, 140);");

    // 修改：线路名称输入框
    QLabel *lineLabel = new QLabel("请输入线路名称:", this);
    lineEdit = new QLineEdit(this);
    lineEdit->setPlaceholderText("请输入线路名称");

    // 新站点名输入框
    QLabel *stationNameLabel = new QLabel("新站点名称:", this);
    stationNameEdit = new QLineEdit(this);
    stationNameEdit->setPlaceholderText("请输入新站点名称");

    // 间隔时间输入框
    QLabel *intervalLabel = new QLabel("与下一站的间隔时间（分钟）:", this);
    intervalEdit = new QLineEdit(this);
    intervalEdit->setPlaceholderText("请输入与下一站的时间间隔");

    // 新增：与上一站的时间间隔输入框
    QLabel *lastIntervalLabel = new QLabel("与上一站的间隔时间（分钟）:", this);
    lastIntervalEdit = new QLineEdit(this);
    lastIntervalEdit->setPlaceholderText("请输入与上一站的时间间隔");

    // 是否在中途添加
    QLabel *midwayLabel = new QLabel("是否在中途添加:", this);
    midwayComboBox = new QComboBox(this);
    midwayComboBox->addItem("否");
    midwayComboBox->addItem("是");

    // 修改：上一站点输入框
    QLabel *lastStationLabel = new QLabel("上一站点:", this);
    lastStationEdit = new QLineEdit(this);
    lastStationEdit->setPlaceholderText("请输入上一站点名称");

    // 修改：下一站点输入框
    QLabel *nextStationLabel = new QLabel("下一站点:", this);
    nextStationEdit = new QLineEdit(this);
    nextStationEdit->setPlaceholderText("请输入下一站点名称");

    // 插入位置选择框（当选择“否”时显示）
    QLabel *insertPositionLabel = new QLabel("选择插入位置:", this);
    insertPositionComboBox = new QComboBox(this);
    insertPositionComboBox->addItem("在起点前");
    insertPositionComboBox->addItem("在末站后");

    // 添加按钮
    QPushButton *addButton = new QPushButton("添加站点", this);
    addButton->setStyleSheet("font-size: 18px;");

    // 布局管理
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(titleLabel);
    layout->addWidget(lineLabel);
    layout->addWidget(lineEdit);        // 线路名称输入框
    layout->addWidget(stationNameLabel);
    layout->addWidget(stationNameEdit);
    layout->addWidget(intervalLabel);
    layout->addWidget(intervalEdit);
    layout->addWidget(midwayLabel);
    layout->addWidget(midwayComboBox);
    layout->addWidget(lastStationLabel);
    layout->addWidget(lastStationEdit); // 上一站点输入框
    layout->addWidget(nextStationLabel);
    layout->addWidget(nextStationEdit); // 下一站点输入框
    layout->addWidget(lastIntervalLabel);
    layout->addWidget(lastIntervalEdit); // 新增上一站时间间隔输入框
    layout->addWidget(insertPositionLabel);
    layout->addWidget(insertPositionComboBox);
    layout->addWidget(addButton);

    // 当选择“是”时，显示插入站点的输入框，选择“否”时显示插入位置的下拉框
    connect(midwayComboBox, &QComboBox::currentTextChanged, this, [=](const QString &text) {
        bool isMidway = (text == "是");
        lastStationLabel->setVisible(isMidway);
        lastStationEdit->setVisible(isMidway);
        nextStationLabel->setVisible(isMidway);
        nextStationEdit->setVisible(isMidway);
        lastIntervalLabel->setVisible(isMidway);  // 显示与上一站的间隔时间输入框
        lastIntervalEdit->setVisible(isMidway);
        insertPositionLabel->setVisible(!isMidway);
        insertPositionComboBox->setVisible(!isMidway);
    });

    // 添加站点功能
    connect(addButton, &QPushButton::clicked, this, [=]() {
        QString lineName = lineEdit->text().trimmed(); // 获取线路名称
        QString stationName = stationNameEdit->text().trimmed();
        QString intervalStr = intervalEdit->text().trimmed();
        bool isIntervalValid = false;
        int interval = intervalStr.toInt(&isIntervalValid);

        if (lineName.isEmpty() || stationName.isEmpty() || !isIntervalValid) {
            QMessageBox::warning(this, "输入错误", "请填写有效的线路名称、站点名称和间隔时间！");
            return;
        }

        if (midwayComboBox->currentText() == "是") {
            // 中途添加逻辑
            QString lastStation = lastStationEdit->text().trimmed();
            QString nextStation = nextStationEdit->text().trimmed();
            QString lastIntervalStr = lastIntervalEdit->text().trimmed();
            bool isLastIntervalValid = false;
            int lastInterval = lastIntervalStr.toInt(&isLastIntervalValid);

            if (lastStation.isEmpty() || nextStation.isEmpty() || !isLastIntervalValid) {
                QMessageBox::warning(this, "输入错误", "请填写上一站和下一站名称及与上一站的时间间隔！");
                return;
            }

            auto it = std::find_if(newLine->stations.begin(), newLine->stations.end(),
                                    [&](const std::pair<std::string, int> &station) {
                                        return station.first == lastStation.toStdString();
                                    });

            if (it != newLine->stations.end() && (it + 1) != newLine->stations.end() &&
                (it + 1)->first == nextStation.toStdString()) {
                // 在指定的两个站点之间插入新站点，并更新上一站的时间间隔
                newLine->stations.insert(it + 1, {stationName.toStdString(), interval});
                it->second = lastInterval;  // 更新上一站点的时间
            }
        } else {
            // 根据用户选择的插入位置，插入站点到起点前或末站后
            if (insertPositionComboBox->currentText() == "在起点前") {
                newLine->stations.insert(newLine->stations.begin(), {stationName.toStdString(), interval});
            } else {
                newLine->stations.push_back({stationName.toStdString(), interval});
            }
        }


        // 清空输入框
        lineEdit->clear();
        stationNameEdit->clear();
        intervalEdit->clear();
        lastStationEdit->clear();
        nextStationEdit->clear();
        lastIntervalEdit->clear();

        // 显示成功提示
        QMessageBox::information(this, "成功", "站点 " + stationName + " 已成功添加！");
    });

    // 隐藏“中途添加”和插入位置选择框，默认显示为“否”
    lastStationLabel->setVisible(false);
    lastStationEdit->setVisible(false);
    nextStationLabel->setVisible(false);
    nextStationEdit->setVisible(false);
    lastIntervalLabel->setVisible(false);  // 隐藏与上一站的时间间隔输入框
    lastIntervalEdit->setVisible(false);
    insertPositionLabel->setVisible(true);
    insertPositionComboBox->setVisible(true);

    setWindowTitle("添加站点");
    resize(400, 400);
}

              // 指针传递 NewLine 对象
QLineEdit *AddStopWindow::lineEdit;             // 线路名称输入框
QLineEdit *AddStopWindow::stationNameEdit;      // 新站点名输入框
QLineEdit *AddStopWindow::intervalEdit;         // 间隔时间输入框
QComboBox *AddStopWindow::midwayComboBox;       // 是否中途添加选择框
QLineEdit *AddStopWindow::lastStationEdit;      // 上一站点输入框
QLineEdit *AddStopWindow::nextStationEdit;      // 下一站点输入框
QLineEdit *AddStopWindow::lastIntervalEdit;     // 与上一站的时间间隔输入框
QComboBox *AddStopWindow::insertPositionComboBox; // 插入位置选择框

// 假设您在 BusAdminSystemWindow 中有现有的线路数据
BusAdminSystemWindow::BusAdminSystemWindow(QWidget *parent) 
{
    QLabel *backgroundLabel = new QLabel(this);
    backgroundLabel->setPixmap(QPixmap("./pics/Bus_white.jpg"));
    backgroundLabel->setScaledContents(true); // 自动调整图片大小以适应窗口
    backgroundLabel->setGeometry(0, 0, 400, 400); // 设置背景图片标签的大小为窗口大小
    // 设置标题
    QLabel *titleLabel = new QLabel("公交线路管理员系统", this);
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setStyleSheet("font-size: 24px; font-weight: bold; color :  #ffffff; background-color: rgba(50, 50, 50, 140);");

    // 创建按钮
    QPushButton *addLineButton = new QPushButton("增加线路", this);
    QPushButton *deleteLineButton = new QPushButton("删除线路", this);
    QPushButton *addStopButton = new QPushButton("添加站点", this);
    QPushButton *deleteStopButton = new QPushButton("删除站点", this);
    QPushButton *modifyBusTimeButton = new QPushButton("修改发车时间", this);

    // 假设您有一个现有的线路对象 newLine
    NewLine *newLine = new NewLine{"线路1", "06:00", "22:00", {{"站点A", 10}, {"站点B", 15}, {"站点C", 20}}};

    // 布局管理
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(titleLabel);
    layout->addWidget(addLineButton);
    layout->addWidget(deleteLineButton);
    layout->addWidget(addStopButton);
    layout->addWidget(deleteStopButton);
    layout->addWidget(modifyBusTimeButton);

    // 连接按钮的信号与槽
    connect(addLineButton, &QPushButton::clicked, this, [=]() {
        AddLineWindow *addLineWindow = new AddLineWindow();
        addLineWindow->show();
    });

    connect(deleteLineButton, &QPushButton::clicked, this, [=]() {
        DeleteLineWindow *deleteLineWindow = new DeleteLineWindow();
        deleteLineWindow->show();
    });

    // 点击“添加站点”按钮时，传递线路信息给 AddStopWindow
    connect(addStopButton, &QPushButton::clicked, this, [=]() {
        AddStopWindow *addStopWindow = new AddStopWindow(newLine);  // 传递 newLine 对象
        addStopWindow->show();
    });

    connect(deleteStopButton, &QPushButton::clicked, this, [=]() {
        DeleteStopWindow *deleteStopWindow = new DeleteStopWindow();
        deleteStopWindow->show();
    });

    connect(modifyBusTimeButton, &QPushButton::clicked, this, [=]() {
        ModifyBusTimeWindow *modifyWindow = new ModifyBusTimeWindow();
        modifyWindow->show();
    });

    setWindowTitle("公交线路管理员系统");
    resize(400, 400);
}

// 路线查询窗口类，用户输入起点和终点，显示查询功能

RouteQueryWindow::RouteQueryWindow(QWidget *parent) 
{QLabel *backgroundLabel = new QLabel(this);
    backgroundLabel->setPixmap(QPixmap("./pics/Bus_water.jpg"));
    backgroundLabel->setScaledContents(true); // 自动调整图片大小以适应窗口
    backgroundLabel->setGeometry(0, 0, 400, 400); // 设置背景图片标签的大小为窗口大小
    QLabel *titleLabel = new QLabel("路线查询", this);
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setStyleSheet("font-size: 24px; font-weight: bold; color :  #ffffff; background-color: rgba(50, 50, 50, 140);");

    QLabel *startLabel = new QLabel("输入起点:", this);
    QLineEdit *startLineEdit = new QLineEdit(this);
    startLineEdit->setPlaceholderText("输入起点");
    startLabel->setStyleSheet("font-size: 24px; font-weight: bold; color :  #ffffff; background-color: rgba(50, 50, 50, 140);");

    QLabel *endLabel = new QLabel("输入终点:", this);
    QLineEdit *endLineEdit = new QLineEdit(this);
    endLineEdit->setPlaceholderText("输入终点");
    endLabel->setStyleSheet("font-size: 24px; font-weight: bold; color :  #ffffff; background-color: rgba(50, 50, 50, 140);");
    

    QPushButton *searchButton = new QPushButton("查询路线", this);

    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(titleLabel);
    layout->addWidget(startLabel);
    layout->addWidget(startLineEdit);
    layout->addWidget(endLabel);
    layout->addWidget(endLineEdit);
    layout->addWidget(searchButton);

    connect(searchButton, &QPushButton::clicked, this, [=]() {
        QString start = startLineEdit->text().trimmed();
        std::string startStdString = start.toStdString();
        startstationname = startStdString;
        QString end = endLineEdit->text().trimmed();
        std::string endStdString = end.toStdString();
        endstationname = endStdString;
        if (start.isEmpty() || end.isEmpty()) {
            QMessageBox::warning(this, "错误", "请输入起点和终点！");
        } else {
            QString routeInfo;
            // std::string info = BusSystem::algorithm::findAllPossibleRoutes(startStdString, endStdString);
            std::string info = "请选择你所要查询的线路";
            routeInfo = QString::fromStdString(info);
            RouteInfoWindow *routeInfoWindow = new RouteInfoWindow(routeInfo);
            routeInfoWindow->show();
        }
    });

    setWindowTitle("路线查询");
    resize(400, 400);
}

// 车次查询窗口类，输入车次后显示详细信息

TrainQueryWindow::TrainQueryWindow(QWidget *parent) 
{
    QLabel *backgroundLabel = new QLabel(this);
    backgroundLabel->setPixmap(QPixmap("./pics/Bus_green.jpg"));
    backgroundLabel->setScaledContents(true); // 自动调整图片大小以适应窗口
    backgroundLabel->setGeometry(0, 0, 400, 400); // 设置背景图片标签的大小为窗口大小
    QLabel *titleLabel = new QLabel("车次查询", this);
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setStyleSheet("font-size: 24px; font-weight: bold; color :  #ffffff; background-color: rgba(50, 50, 50, 140);");

    QLabel *routeLabel = new QLabel("输入车次:", this);
    QLineEdit *routeLineEdit = new QLineEdit(this);
    routeLineEdit->setPlaceholderText("输入车次");

    QPushButton *startQueryButton = new QPushButton("查询车次", this);
    startQueryButton->setStyleSheet("font-size: 18px;");

    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(titleLabel);
    layout->addWidget(routeLabel);
    layout->addWidget(routeLineEdit);
    layout->addWidget(startQueryButton);

    connect(startQueryButton, &QPushButton::clicked, this, [=]() {
        QString route = routeLineEdit->text().trimmed();
        std::string routeStdString = route.toStdString();
        if (route.isEmpty()) {
            QMessageBox::warning(this, "错误", "请输入车次！");
        } else {
            // 模拟查询车次信息
            QString trainInfo;
            std::string info = BusSystem::algorithm::queryBusLineDetails(routeStdString);
            trainInfo = QString::fromStdString(info);
            TrainInfoWindow *trainInfoWindow = new TrainInfoWindow(trainInfo);
            trainInfoWindow->show();
        }
    });

    setWindowTitle("车次查询");
    resize(400, 300);
}

// 主窗口类，显示用户和管理员的不同界面，并添加图片
MainAppWindow::MainAppWindow(bool isAdmin, QWidget *parent) 
{
    QLabel *titleLabel = new QLabel("公交路线自动化选择系统", this);
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setStyleSheet("font-size: 24px; font-weight: bold; background-color: rgba(50, 50, 50, 180);");

    QPushButton *routeQueryButton = new QPushButton("路线查询", this);
    routeQueryButton->setStyleSheet("font-size: 18px;");

    QPushButton *trainQueryButton = new QPushButton("车次查询", this);
    trainQueryButton->setStyleSheet("font-size: 18px;");

    QPushButton *routeManageButton;
    if (isAdmin) {
        routeManageButton = new QPushButton("路线管理", this);
        routeManageButton->setStyleSheet("font-size: 18px;");
    }

    QLabel *imageLabel = new QLabel(this);
    QPixmap pixmap("./pics/BabyBus.png");

    if (!pixmap.isNull()) {
        imageLabel->setPixmap(pixmap);
        imageLabel->setScaledContents(true);
        imageLabel->setFixedSize(300, 300);
    } else {
        imageLabel->setText("图片加载失败");
    }

    QVBoxLayout *buttonLayout = new QVBoxLayout();
    buttonLayout->addWidget(routeQueryButton);
    buttonLayout->addWidget(trainQueryButton);

    if (isAdmin) {
        buttonLayout->addWidget(routeManageButton);
    }

    QHBoxLayout *contentLayout = new QHBoxLayout();
    contentLayout->addLayout(buttonLayout);
    contentLayout->addWidget(imageLabel);

    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(titleLabel);
    mainLayout->addLayout(contentLayout);

    setWindowTitle("Main Application");
    resize(600, 400);

    connect(routeQueryButton, &QPushButton::clicked, this, [=]() {
        RouteQueryWindow *routeQueryWindow = new RouteQueryWindow();
        routeQueryWindow->show();
    });

    connect(trainQueryButton, &QPushButton::clicked, this, [=]() {
        TrainQueryWindow *trainQueryWindow = new TrainQueryWindow();
        trainQueryWindow->show();
    });

    if (isAdmin) {
        connect(routeManageButton, &QPushButton::clicked, this, [=]() {
            BusAdminSystemWindow *adminWindow = new BusAdminSystemWindow();
            adminWindow->show();
        });
    }
}

LoginWindow::LoginWindow(QWidget *parent) 
{
    QLabel *backgroundLabel = new QLabel(this);
    backgroundLabel->setPixmap(QPixmap("./pics/Bus_Aut.jpg"));
    backgroundLabel->setScaledContents(true); // 自动调整图片大小以适应窗口
    backgroundLabel->setGeometry(0, 0, 600, 400); // 设置背景图片标签的大小为窗口大小

    QLabel *titleLabel = new QLabel("公交车查询系统", this);
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setStyleSheet("font-size: 24px; font-weight: bold; color :  #ffffff; background-color: rgba(50, 50, 50, 140);");

    QLabel *usernameLabel = new QLabel("用户名:", this);
    QLineEdit *usernameLineEdit = new QLineEdit(this);
    usernameLabel->setStyleSheet("font-weight: bold; color :#000000; ");

    QLabel *passwordLabel = new QLabel("密码:", this);
    QLineEdit *passwordLineEdit = new QLineEdit(this);
    passwordLineEdit->setEchoMode(QLineEdit::Password);
    passwordLabel->setStyleSheet("font-weight: bold; color:#000000;");

    QPushButton *loginButton = new QPushButton("登录", this);
    QPushButton *guestLoginButton = new QPushButton("游客登录", this);

    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(titleLabel);
    layout->addWidget(usernameLabel);
    layout->addWidget(usernameLineEdit);
    layout->addWidget(passwordLabel);
    layout->addWidget(passwordLineEdit);

    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->addWidget(loginButton);
    buttonLayout->addWidget(guestLoginButton);
    layout->addLayout(buttonLayout);

    // 创建用户数据，包含用户名、密码和是否管理员的信息
    struct User {
        QString password;
        bool isAdmin;
    };

    QMap<QString, User> users;
    users.insert("admin", {"password123", true}); // 管理员用户
    users.insert("user1", {"password123", false}); // 普通用户

    // 登录按钮点击事件
    connect(loginButton, &QPushButton::clicked, this, [=]() {
        QString username = usernameLineEdit->text().trimmed();
        QString password = passwordLineEdit->text().trimmed();

        if (!users.contains(username)) {
            QMessageBox::warning(this, "登录失败", "用户名无效");
            return;
        }

        // 验证密码
        User user = users.value(username);
        if (user.password != password) {
            QMessageBox::warning(this, "登录失败", "密码错误");
            return;
        }

        // 登录成功，打开主窗口
        bool isAdmin = user.isAdmin;
        MainAppWindow *mainAppWindow = new MainAppWindow(isAdmin);
        mainAppWindow->show();
        this->close();
    });

    // 游客登录按钮点击事件
    connect(guestLoginButton, &QPushButton::clicked, this, [=]() {
        MainAppWindow *mainAppWindow = new MainAppWindow(false);
        mainAppWindow->show();
        this->close();
    });

    setWindowTitle("登录");
    resize(600, 400);
}

#include "main.moc"



